import markdownIdContainer from "markdown-it-container"
import { Markdown } from "vuepress/markdown"
import fs from 'fs'
import path from 'path'
import { highlight } from "../utils/highlight"

export default {
    name: "container",
    extendsMarkdown: (md: Markdown) => {
        md.use(markdownIdContainer, "demo", {
            validate(params) {
                return params.trim().match(/^demo\s*(.*)$/);
            },
            render(tokens, idx) {
                if (tokens[idx].nesting === 1) {
                    const sourceFileToken = tokens[idx + 2]
                    const sourceFile = sourceFileToken.children?.[0].content ?? ''
                    let source = fs.readFileSync(
                        path.resolve("docs/.vuepress/components", `./examples/${sourceFile}.vue`),
                        'utf-8'
                    )
                    return `<Demo file="${sourceFile}" source="${encodeURIComponent(highlight(source, 'vue'))}">`
                }
                return `</Demo>`;
            }
        })
    },
}
